package com.yanqu.road.server.manager.activity.newyearbag;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.utils.date.DateHelper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossNewYearBagMgr extends TempCrossMgr {

    private static final Map<Integer, CrossNewYearBagActivity> activityMap = new ConcurrentHashMap<>();

    public static synchronized CrossNewYearBagActivity getActivity(int activityId) {
        if (!activityMap.containsKey(activityId)) {
            // 读配置 获取活动信息 保证有活动信息
            ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
            if (activityInfo == null) {
                return null;
            }
            CrossNewYearBagActivity activity = new CrossNewYearBagActivity(activityInfo);
            activityMap.put(activityId, activity);
        }
        return activityMap.get(activityId);
    }

    @Override
    public boolean save() {
        for (CrossNewYearBagActivity activity : activityMap.values()) {
            try {
                activity.save();
            } catch (Exception e) {
                getLogger().error("error : ", e);
            }
        }
        return true;
    }

    @Override
    public boolean removeExpireData() throws Exception {
        for (CrossNewYearBagActivity activity : activityMap.values()) {
            try {
                ActivityInfo activityInfo = activity.getConfig().getActivityInfo();
                long removeTime = activityInfo.getEndShowTime() * 1000 + DateHelper.HOUR_MILLIONS * 12;
                if (System.currentTimeMillis() > removeTime) {
                    activity.save(); // 保存完才能移除啊啊啊
                    activityMap.remove(activityInfo.getActivityId());
                    getLogger().debug("remove cross new year bag activity id {}.", activityInfo.getActivityId());
                }
            } catch (Exception e) {
                getLogger().error("error : ", e);
            }
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        for (CrossNewYearBagActivity activity : activityMap.values()) {
            try {
                ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activity.getConfig().getActivityInfo().getActivityId());
                activity.reloadConfig(activityInfo);
            } catch (Exception e) {
                getLogger().error("error : ", e);
            }
        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
